﻿// Copyright (c) Microsoft Corporation.  All rights reserved.
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using EdmMetadataHelpers;
using System.Collections.Specialized;
using System.IO;
using System.Data.Metadata.Edm;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            LoadTreeView();
            HideAllDivs();
            ShowNode(SelectedNode);
        }
    }
    protected TreeNode SelectedNode {
        get {
            return trCSDL.SelectedNode;
        }
    }
    protected void ShowNode(TreeNode node)
    {
        if (SelectedNode == null) return;
        //At this stage only the Model and EntitySet
        //nodes have any content (right hand side)
        switch (node.Target)
        { 
            case "":
            case "EntityType":
            case "AssociationType":
                break;
            case "Model":
                ShowModel(node);
                break;
            case "EntitySet" :
            case "AssociationSet":
                ShowEntitySet(node);
                break;
        }

    }
    /// <summary>
    /// Shows the EntitySet
    /// </summary>
    protected void ShowEntitySet(TreeNode node)
    {
        //Hide results
        grdResults.Visible = false;
        //Show actions
        divEntitySet.Visible = true;

        //Gets the appropriate Wrapper by using the parent (EntityContainer)'s parent node
        //text, which is the name you gave the Edm in question
        EdmWrapper edm = EdmWrappers.Current.FindByName(node.Parent.Parent.Text);
        //Get the name of the EntitySet and the name of the Container
        string entityset = node.Value;
        string container = node.Parent.Value;
        //Use to construct a default query
        txtQuery.Text = string.Format("select VALUE E from {0}.{1} as E", container, entityset);
        //Find the entity set by name
        EntitySet es = edm.Csdl.EntitySets.Where(n => n.Name == node.Text).FirstOrDefault();
        if (es == null) 
            throw new Exception(string.Format("No EntitySet called {0} was found", node.Text));
        
        //Now create a checkbox for each property in the Entity associated with that entity set
        EntityType et = es.ElementType as EntityType;
        this.chkEntitySetColumns.Items.Clear();
        
        foreach (EdmProperty prop in et.Properties)
            this.chkEntitySetColumns.Items.Add(new ListItem(prop.Name, prop.Name));
    }
    protected void chkEntitySetColumns_SelectedChanged(Object sender, EventArgs e)
    {
        //We simply rebuild the eSQL based on what properties are selected
        string eSQL = null;
        foreach(ListItem item in chkEntitySetColumns.Items){
            if (item.Selected) 
                eSQL = eSQL == null ? string.Format("E.{0}", item.Value) : string.Format("{0}, E.{1} ",eSQL,item.Value);

        }
        //If no properties are selected we get the whole entity using VALUE
        if (eSQL == null) eSQL = "VALUE E";

        string container = SelectedNode.Parent.Text;
        string name = SelectedNode.Text;
        string fullname = container + "." + name;
        eSQL = string.Format("SELECT {0} FROM {1} AS E", eSQL, fullname);
        this.txtQuery.Text = eSQL;
    }

    protected void ShowModel(TreeNode node)
    {
        Response.Redirect(string.Format("EditModel.aspx?Model={0}", node.Value));
    }
    protected void HideAllDivs()
    {
        this.divEntitySet.Visible = false;
    }
    protected void LoadTreeView()
    {
        //Create a root node
        TreeNode root = new TreeNode("All Models");
        root.SelectAction = TreeNodeSelectAction.Select;
        root.Target = "";
        //Create a "Add a model" node
        TreeNode action = new TreeNode("[Add a model]");
        action.ImageUrl = @"assets\newschema.jpg";
        action.SelectAction = TreeNodeSelectAction.Select;
        action.Target = "Model";

        root.ChildNodes.Add(action);
        //Insure there is at least one Edm registered
        if (EdmWrappers.Current.Count == 0)
            EdmWrappers.Current.Add(new EdmWrapper(
                "Northwind",
                "System.Data.SqlClient",
                @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.MDF;Integrated Security=True;User Instance=True",
                @"|DataDirectory|\NorthwindModel.csdl",
                @"|DataDirectory|\NorthwindModel.ssdl",
                @"|DataDirectory|\NorthwindModel.msl")
        );

        
        //Loop over th registered edms and add a not for each of them


        foreach (EdmWrapper edm in EdmWrappers.Current)
            root.ChildNodes.Add(edm.GetRootNode());

        trCSDL.Nodes.Add(root);
    }

    protected void btnExecuteQuery_Click(object sender, EventArgs e)
    {
        grdResults.Visible = true;
        string edmName = SelectedNode.Parent.Parent.Value;
        string eSQL = txtQuery.Text.Trim();
        DataTable table = EdmWrappers.Current.FindByName(edmName).GetDataTable(eSQL);
        this.grdResults.DataSource = table;
        this.grdResults.DataBind();
    }

    protected void OnNodeSelect(object sender, EventArgs e)
    {
        HideAllDivs();
        ShowNode(SelectedNode);
    }

}
